# 用方向键控制方块移动
# 方向键松开, 停止移动
# 碰撞后减1分, 重新碰撞再减一分
# 另一个小方块实现追逐

import pygame
import sys

from pygame_test.MoveRect import MoveRect
from pygame_test.pygame_09_two_rects_02 import two_rects


def move():
    pygame.init()
    winx = 300
    winy = 300
    screen = pygame.display.set_mode((winx, winy))
    fclock = pygame.time.Clock()
    speedx = 5
    speedy = 5
    b = 'still' # 大方块运动状态标记
    f = 10  # 分数
    c = 'no'  # 碰撞标记
    is_in = True  #  是否在窗口内
    r2speedx = 1
    r2speedy = 1
    rect1 = MoveRect(55, 66, 20, 25, (255, 0, 255))
    rect2 = MoveRect(10, 20, 10, 10, (255, 255, 255))
    while True:
        screen.fill((0, 0, 0))
        rect1.draw(screen)
        directx, directy = two_rects(rect2.get_rect(), rect1.get_rect())
        rect2.move(r2speedx * directx, r2speedy * directy)
        rect2.draw(screen)
        # 判断是否在屏幕内
        if not rect1.is_in(0, 0, winx, winy) and f > 0:
            if is_in:
                f -= 1
                is_in = False
                print(f)
        else:
            is_in = True
        # print(rect1.is_in(winx,winy))
        if rect1.is_collide(rect2.get_rect()) and f > 0:
            if c == 'no':
                f -= 1
                print('collide', f, c)
                c = 'yes'
        else:
            c = 'no'
        if f > 0:
            if b == 'down':
                rect1.move(0, speedy)
            elif b == 'up':
                rect1.move(0, -speedy)
            elif b == 'left':
                rect1.move(-speedx, 0)
            elif b == 'right':
                rect1.move(speedx, 0)
        else:
            print('游戏结束!')

        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if e.type == pygame.KEYDOWN:
                if e.key == pygame.K_DOWN:
                    b = 'down'
                elif e.key == pygame.K_UP:
                    b = 'up'
                elif e.key == pygame.K_LEFT:
                    b = 'left'
                elif e.key == pygame.K_RIGHT:
                    b = 'right'
                if e.key == pygame.K_SPACE:
                    print(rect1.get_rect())
            elif e.type == pygame.KEYUP:
                if e.key in [pygame.K_DOWN, pygame.K_UP, pygame.K_RIGHT, pygame.K_LEFT]:
                    b = 'still'
        pygame.display.update()
        fclock.tick(10)


if __name__ == '__main__':
    move()
